package com.xcfw.dorm.util;

import com.xcfw.dorm.entity.Student;
import com.xcfw.dorm.seviceimpl.dormcenter.StudentSeriviceImpl;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: Dorm
 * @description: 工具类
 * @author: Bruse Queen
 * @create: 2018-04-07 13:30
 **/
@Service
public class DormUtil {
    @Autowired
    private StudentSeriviceImpl zsgcService;

    public static boolean juedeNull(String string) {
        if (string == null || "".equals(string)) {
            return true;
        }
        return false;
    }


    public static Integer getInteget(String str) {
        String str2 = "";
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    str2 += str.charAt(i);
                }
            }
        }
        return "".equals(str2) ? 0 : Integer.parseInt(str2.substring(0, 8));
    }

    /**
     * 获取uuid
     *
     * @return uuid
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String setNull(Integer integer) {
        return integer == null ? null : String.valueOf(integer);
    }


    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public static boolean isChinese(String str) {
        // 利用正则表达式判断输入内容
        String reg = "^[\u4e00-\u9fff/]+$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    public static List<Map<String, String>> addCharacter(List<Map<String, String>> list) {
        List<Map<String, String>> listTemp = new ArrayList<>();
        for (Map map : list) {
            Map<String, String> newMap = new HashMap<>();
            Set<String> keySetTemp = map.keySet();

            for (String key : keySetTemp) {
                newMap.put("#" + key, map.get(key).toString());
            }
            listTemp.add(newMap);
        }
        return listTemp;
    }

    /**
     * 替换Excel模板文件内容
     *
     * @param list           文档数据
     * @param sourceFilePath Excel模板文件路径
     * @param targetFilePath Excel生成文件路径
     */
    public static boolean excelReplace(List<Map<String, String>> list, String sourceFilePath, String targetFilePath) {
        List<Map<String, String>> listTemp = DormUtil.addCharacter(list);

        boolean bool = true;
        try {
            // 实例化表格对象
            Workbook wb;
            if (sourceFilePath.matches("^.+\\.(?i)(xlsx)$")) {
                wb = new XSSFWorkbook(new FileInputStream(sourceFilePath));
            } else {
                wb = new HSSFWorkbook(new FileInputStream(sourceFilePath));
            }

            // 遍历取出表格所有的sheet
            List<Sheet> sheet = new ArrayList<>();
            for (Sheet sheetTemp : wb) {
                sheet.add(sheetTemp);
            }

            int i = 0;
            for (Sheet sheetTemp : sheet) {
                Map item = listTemp.get(i);
                replace(item, sheetTemp);
                i++;
            }

            for (Sheet sheetTemp : sheet) {
                replaceSurplus(sheetTemp);
            }

            // 输出文件
            FileOutputStream fileOut = new FileOutputStream(targetFilePath);
            wb.write(fileOut);
            fileOut.close();

        } catch (Exception e) {
            bool = false;
            e.printStackTrace();
        }
        return bool;
    }

    private static void replace(Map<String, String> newMap, Sheet sheet) {

        // 遍历sheet
        Iterator rows = sheet.rowIterator();
        // 遍历每行
        while (rows.hasNext()) {
            Row row = (Row) rows.next();
            // 如果此行不为空
            if (row != null) {
                int num = row.getLastCellNum();
                //  去除每个单元格
                for (int i = 0; i < num; i++) {
                    Cell cell = row.getCell(i);
                    // 不为空设置数据类型
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    }
                    // 单元格为空进行下次循环
                    if (cell == null || cell.getStringCellValue() == null) {
                        continue;
                    }
                    // 取出单元格中的值
                    String value = cell.getStringCellValue();
                    // 如果不是空串
                    if (!"".equals(value)) {

                        Set<String> keySet = newMap.keySet();
                        Iterator<String> it = keySet.iterator();
                        // 遍历替换文本
                        while (it.hasNext()) {
                            String text = it.next();
                            if (value.equalsIgnoreCase(text)) {
                                cell.setCellValue((String) newMap.get(text));
                                break;
                            }
                        }


                    } else {
                        cell.setCellValue("");
                    }
                }
            }
        }
    }

    public static void replaceSurplus(Sheet sheet) {
        // 遍历sheet
        Iterator rows = sheet.rowIterator();
        // 遍历每行
        while (rows.hasNext()) {
            Row row = (Row) rows.next();
            // 如果此行不为空
            if (row != null) {
                int num = row.getLastCellNum();
                //  去除每个单元格
                for (int i = 0; i < num; i++) {
                    Cell cell = row.getCell(i);
                    // 不为空设置数据类型
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    }
                    // 单元格为空进行下次循环
                    if (cell == null || cell.getStringCellValue() == null) {
                        continue;
                    }
                    // 取出单元格中的值
                    String value = cell.getStringCellValue();
                    // 如果不是空串
                    if (!"".equals(value)) {

                        if (value.contains("#")) {
                            cell.setCellValue("");
                        }


                    } else {
                        cell.setCellValue("");
                    }
                }
            }
        }

    }

    /**
     * @param
     * @return void
     * @Description: 创建相关文件夹
     * @Author: Bruse Queen
     * @Date: 2018/3/23-15:37
     */
    public static void mkFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void readExcel(String sourceFilePath) {
        try {
            // 实例化表格对象
            Workbook wb;
            if (sourceFilePath.matches("^.+\\.(?i)(xlsx)$")) {
                wb = new XSSFWorkbook(new FileInputStream(sourceFilePath));
            } else {
                wb = new HSSFWorkbook(new FileInputStream(sourceFilePath));
            }


            // 遍历取出表格所有的sheet
            List<Sheet> sheet = new ArrayList<>();
            for (Sheet sheetTemp : wb) {
                sheet.add(sheetTemp);
            }

            for (Sheet sheetTemp : sheet) {
                // 遍历sheet
                Iterator rows = sheetTemp.rowIterator();
                // 遍历每行
                while (rows.hasNext()) {
                    Row row = (Row) rows.next();
                    // 如果此行不为空
                    if (row != null) {

                        int num = row.getLastCellNum();
                        //  去除每个单元格
                        for (int i = 0; i < num; i++) {
                            Cell cell = row.getCell(i);
                            // 不为空设置数据类型
                            if (cell != null) {
                                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            }
                            // 单元格为空进行下次循环
                            if (cell == null || cell.getStringCellValue() == null) {
                                continue;
                            }
                            // 取出单元格中的值
                            String value = cell.getStringCellValue();
                            if (value != "" && isInteger(value)) {
                                String name = row.getCell(i + 1).getStringCellValue();
                                String classNmae = row.getCell(i + 2).getStringCellValue();
                                if (name != "" && classNmae != "") {
                                    System.out.println("博宁8-" + value + " " + name + " " + classNmae);

                                    Student student = new Student();
                                    student.setBuilding("博宁8");
                                    student.setDormitory(Short.parseShort(value));
                                    student.setName(name);
                                    student.setStudentClass(classNmae);
                                    zsgcService.add(student);
                                }

                                String name1 = row.getCell(i + 3).getStringCellValue();
                                String classNmae1 = row.getCell(i + 4).getStringCellValue();
                                if (name1 != "" && classNmae1 != "") {
                                    System.out.println("博宁8-" + value + " " + name1 + " " + classNmae1);

                                    Student student = new Student();
                                    student.setBuilding("博宁8");
                                    student.setDormitory(Short.parseShort(value));
                                    student.setName(name1);
                                    student.setStudentClass(classNmae1);
                                    zsgcService.add(student);
                                }

                            }
                        }
                        System.out.println();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
